﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using 易发车网.Untils;
using 易发车网.WebResult;
using 易发车网.WebSpider;

namespace 易发车网.Pages
{
    public partial class FormMain : Form
    {
        #region 变量 & 属性
        private List<string> Temp_BanBrands = new List<string>();
        private List<SellInfo> Temp_SellInfoList = new List<SellInfo>();
        private List<SellInfo> Temp_WantedListItems = new List<SellInfo>();
        private List<SellDetial> Temp_WantedListDetials = new List<SellDetial>();

        private int PauseTime = 45;
        #endregion

        #region 初始化
        public FormMain()
        {
            InitializeComponent();
            Temp_BanBrands = AppData.UserSet.BanBrands;
            TextBox_Mail.Lines = AppData.UserSet.Emails.ToArray();
            Combox_Year.DropDownStyle = ComboBoxStyle.DropDownList;
            NumericUpDown_ViewCount.Maximum = 99999;
            NumericUpDown_CarNum.Maximum = 999999;
            NumericUpDown_MinDiscount.Maximum = 999999;
            Btn_SaveFilter.Click += Btn_SaveFilter_Click;
            Btn_Start.Click += Btn_Start_Click;
            linkLabel1.LinkClicked += linkLabel1_LinkClicked;
            Linklabel_BanBrand.LinkClicked += Linklabel_BanBrand_LinkClicked;
            CreateYear();
            HaiMail.Read();
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 创建年份
        /// </summary>
        private void CreateYear()
        {
            Combox_Year.Items.Clear();
            for (int i = DateTime.Now.Year; i >= 2000; i--)
            {
                Combox_Year.Items.Add(i);
            }
            Combox_Year.SelectedItem = AppData.UserSet.Year;
            NumericUpDown_CarNum.Value = AppData.UserSet.MaxCarNum;
            NumericUpDown_ViewCount.Value = AppData.UserSet.MostViewCount;
            NumericUpDown_MinDiscount.Value = AppData.UserSet.LeastDiscount;
        }

        /// <summary>
        /// 监视
        /// </summary>
        /// <param name="year"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        private async Task WatchNew(int year, int i)
        {
            var page = i;
            Console.WriteLine(page);
            var api = new _28CarApi();
            while (true)
            {
                try
                {
                    var result = await api.GetSellList(page, year);
                    if (result == null)
                    {
                        Console.WriteLine("等待下一次");
                        await Task.Delay(PauseTime * 1000);
                        continue;
                    }
                    Temp_SellInfoList.AddRange(result);
                    Console.WriteLine("等待下一次拉取列表信息");
 
                    await Task.Delay(PauseTime * 1000);
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="detial"></param>
        private async Task SendMails(SellDetial detial, SellInfo item)
        {
            // 发邮件
            try
            {
                ListViewItem lv = new ListViewItem();
                lv.SubItems[0].Text = item.CarName;
                lv.SubItems.Add(detial.UpdateTime);
                lv.SubItems.Add(detial.Year);
                lv.SubItems.Add("HKD$" + detial.Price.ToString());
                lv.SubItems.Add(detial.Tel);
                lv.SubItems.Add(detial.Url);

                listView1.Invoke((Action)(() =>
                {
                    listView1.Items.Add(lv);
                }));
                var contentStr = CreateContent(detial);
                HaiMail.SendMail(AppData.UserSet.Emails, CreateSubject(detial), contentStr,(int)numericUpDown1.Value);
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送失败" + ex.ToString()) ;
            }
            await Task.Delay(3000);

        }

        /// <summary>
        /// 创建邮件内容
        /// </summary>
        /// <param name="detial"></param>
        /// <returns></returns>
        private string CreateContent(SellDetial detial)
        {
            var content = "";
            content += $"<p>編號:{detial.SellNum}</p>";
            content += $"<p>車類:{detial.CarType}</p>";
            content += $"<p>車廠:{detial.CarBrand}</p>";
            content += $"<p>型號:{detial.Model}</p>";
            content += $"<p>座位:{detial.Seat}</p>";
            content += $"<p>容積:{detial.Volume}</p>";
            content += $"<p>傳動:{detial.Transmission}</p>";
            content += $"<p>年份:{detial.Year}</p>";
            content += $"<p>售價:{detial.Price},原價{detial.OriginPrice},減價:{detial.Discount}</p>";
            content += $"<p>簡評:{detial.Title}</p>";
            content += $"<p>聯絡人資料:{detial.Tel}</p>";
            content += $"<p><a href=\"https://wa.me/852{detial.Tel}\"><p>whatsapp</p></a></p>";
            content += $"<p>更新日期:{detial.UpdateTime}</p>";
            content += $"<p>網址:{detial.Url}</p>";
            content += $"<p><Img src=\"{detial.ImgUrl}\"></p>";
            return content;
        }

        /// <summary>
        /// 创建标题
        /// </summary>
        /// <param name="detial"></param>
        /// <returns></returns>
        private string CreateSubject(SellDetial detial)
        {
            var isDiscount = detial.Discount > 0 ? "減價車" : "新車";
            return $"[{isDiscount}] {detial.Year} {detial.Model} ";
        }
        #endregion

        #region 控件事件
        /// <summary>
        /// 编辑过滤品牌
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Linklabel_BanBrand_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (var fb = new FormBan(Temp_BanBrands))
            {
                if (fb.ShowDialog() == DialogResult.OK)
                {
                    Temp_BanBrands = fb.BanList;
                }
            }
        }

        /// <summary>
        /// 保存筛选设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_SaveFilter_Click(object sender, EventArgs e)
        {
            AppData.UserSet.BanBrands = Temp_BanBrands;
            AppData.UserSet.LeastDiscount = (int)NumericUpDown_MinDiscount.Value;
            AppData.UserSet.MaxCarNum = (int)NumericUpDown_CarNum.Value;
            AppData.UserSet.Year = (int)Combox_Year.SelectedItem;
            AppData.UserSet.Emails = TextBox_Mail.Lines.ToList();
            AppData.UserSet.MostViewCount = (int)NumericUpDown_ViewCount.Value;
            if (AppData.SaveUserSet())
            {
                MessageBox.Show("保存成功");
            }
            else
            {
                MessageBox.Show("保存失败");
            }
        }

        /// <summary>
        /// 检测邮箱
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            panel3.Enabled = false;
            linkLabel1.Text = "检测中...";
            Task.Run(() =>
            {
                try
                {

                    // return;
                    HaiMail.SendMail(AppData.UserSet.Emails, "Test Email", "这是一封测试邮件,当你收到这封邮件时，说明你测试成功!",(int)numericUpDown1.Value);
            
                    MessageBox.Show("测试邮件已发送到您邮箱,请查收");
                }
                catch(Exception ex)
                {
                    MessageBox.Show($"测试失败.{ex.ToString()}");
                }
                this.Invoke((Action)(() =>
                {
                    panel3.Enabled = true;
                    linkLabel1.Text = "测试邮箱是否可用";
                }));
            });

        }

        /// <summary>
        /// 启动监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Btn_Start_Click(object sender, EventArgs e)
        {
            panel3.Enabled = false;
            label8.Text = "系统已启动";
            Btn_Start.Enabled = false;
            // HaiProxy.authHeader("123","123",1,"123");
            var year = (int)Combox_Year.SelectedItem;
            await Task.Run((Action)(async () =>
            {
                // await SaceCache(year, 1);
                await WatchNew(year, 1);
            }));

            await Task.Run((Action)(async () =>
            {
                await SendAllMails();
            }));

            await Task.Run((Action)(async () =>
            {
                await CheckNew();
            }));
        }

        /// <summary>
        /// 排队发送邮件
        /// </summary>
        /// <returns></returns>
        private async Task SendAllMails()
        {
            while (true)
            {
                try
                {
                    if (Temp_WantedListDetials.Count < 1 || Temp_WantedListItems.Count < 1)
                    {
                        await Task.Delay(3000);
                        continue;
                    }

                    var item = Temp_WantedListItems[0];
                    var detial = Temp_WantedListDetials[0];
                    await SendMails(detial, item);

                    Temp_WantedListItems.RemoveAt(0);
                    Temp_WantedListDetials.RemoveAt(0);
                    await Task.Delay(3000);
                }
                catch
                {

                }
            }
        }

        /// <summary>
        /// 检测新买家
        /// </summary>
        /// <returns></returns>
        private async Task CheckNew()
        {

            var api = new _28CarApi();
            while (true)
            {
                try
                {
                    if (Temp_SellInfoList.Count < 1)
                    {
                        await Task.Delay(2000);
                        continue;
                    }

                    var item = Temp_SellInfoList[0];

                    #region 检查是否是老数据了
                    // 判断是否记录过了
                    if (AppData.IsRecordExists(item))
                    {
                        Console.WriteLine($"{item.CarName},{item.Vid},已经发布过了");
                        Temp_SellInfoList.RemoveAt(0);
                        continue;
                    }
                    #endregion

                    #region 读取详细信息
                    // 读取列表信息
                    var detial = await api.GetPhoneByVid(item.Vid);

                    // 判断结果结果是为空
                    if (detial == null)
                    {
                        Temp_SellInfoList.RemoveAt(0);
                        continue;
                    }
                    Console.WriteLine($"{item.Vid},{item.CarName}");
                    #endregion

                    #region 保存这个Vid至数据库
                    AppData.AddRecord(item);
                    AppData.SaveSellRecords();
                    #endregion

                    #region 检查数据量是否超标
                    if (item.ViewCount > AppData.UserSet.MostViewCount)
                    {
                        if ((detial.Discount < AppData.UserSet.LeastDiscount))
                        {
                            Console.WriteLine($"{item.CarName} 浏览数超标 {item.ViewCount}");
                            Temp_SellInfoList.RemoveAt(0);
                            continue;
                        }
                    }
                    #endregion

                    #region 检查是否是不需要的车牌
                    var brand = item.CarName.TrimStart(' ').Split(' ')[0].Trim();
                    if (AppData.UserSet.BanBrands.Exists(b => b.Trim() == brand))
                    {
                        Console.WriteLine($"{item.CarName} 这个车牌子不需要");
                        Temp_SellInfoList.RemoveAt(0);
                        continue;
                    }
                    #endregion

                    #region 判断是否降价处理
                    // 先判断 是否是降价卖的车 ,如果是 降价幅度够不够
                    if (detial.Discount != 0 && detial.Discount < AppData.UserSet.LeastDiscount)
                    {
                        Console.WriteLine($"{item.CarName},降价车,但是降价幅度不够。{detial.Price},{detial.Discount}");
                        Temp_SellInfoList.RemoveAt(0);
                        continue;
                    }


                    #endregion

                    #region 判断是否为私人卖家
                    // 判断这个手机号是否有多个车辆在售
                    var carnum = await api.GetSellListByPhone(detial.Tel);
                    if (carnum <= AppData.UserSet.MaxCarNum)
                    {
                        try
                        {
                            // 添加到邮件发送列表
                            Temp_WantedListItems.Add(item);
                            Temp_WantedListDetials.Add(detial);

                            Temp_SellInfoList.RemoveAt(0);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            Temp_SellInfoList.RemoveAt(0);
                        }
                        Console.WriteLine("Wu!!!");
                    }
                    else
                    {
                        Console.WriteLine($"{item.CarName},非私人卖家{detial.Tel}({carnum})");
                        Temp_SellInfoList.RemoveAt(0);
                    }

                    #endregion

                }
                catch
                {

                }
                await Task.Delay(2000);
            }
        }

        /// <summary>
        /// 缓存第一波
        /// </summary>
        /// <param name="year"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        private async Task SaceCache(int year, int page)
        {
            try
            {
                var api = new _28CarApi();
                var result = await api.GetSellList(page, year);
                if (result != null)
                {
                    AppData.AddRecords(result);
                    AppData.SaveSellRecords();
                }
            }
            catch
            {

            }
        }
        #endregion
    }
}